package org.egedede.processmanager.logs;

import java.util.*;

import org.joda.time.*;

public class ProcessLog{

	private List<ProcessLogListener> listeners = new LinkedList<ProcessLogListener>();
	
	private final List<LogEntry> entries = new LinkedList<LogEntry>();
	public void log(Object o){
		this.log("TRACE",o);
	}
	public void log(String level, Object o){
		LogEntry entry = new LogEntry(level,o.toString(),new DateTime());
		entries.add(entry);
		fireEvent(new ProcessLogEvent(ProcessLogEvent.NEW,this,entry));
	}
	public List<LogEntry> entries(){
		return Collections.unmodifiableList(entries);
	}
	public void reset(){
		entries.clear();
		fireEvent(new ProcessLogEvent(ProcessLogEvent.CLEAR, this,null));
	}
	
	private void fireEvent(ProcessLogEvent event){
		for(ProcessLogListener listener : listeners){
			listener.logUpdated(event);
		}
	}
	
	public void addListener(ProcessLogListener listener){
		listeners.add(listener);
	}
	
	public void removeListener(ProcessLogListener listener){
		listeners.remove(listener);
	}
	
	public String toString(){
		StringBuilder builder = new StringBuilder();
		builder.append("Logs : \n");
		for(LogEntry entry : entries){
			if(entry==null){
				builder.append("NULL : Too bad").append("\n");
			}else{
				builder.append(entry).append("\n");
			}
		}
		return builder.toString();
	}
	
	public String toLongString(){
		StringBuilder builder = new StringBuilder();
		builder.append("Logs : \n");
		for(LogEntry entry : entries){
			if(entry==null){
				builder.append("NULL : Too bad").append("\n");
			}else{
				builder.append(entry.toLongString()).append("\n");
			}
		}
		return builder.toString();
	}
}